﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Data;
using SmugMugApiWrapper;
using System.Reflection;


namespace stsm
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine();
            Console.WriteLine("There are {0} arguments", args.Length);

            if (args.Length % 2 != 0)
            {
                Console.WriteLine("Invalid Arguments.");
                printUsage();
                return;
            }

            Dictionary<string, string> arguments = Utilities.getOptionList(args);

            foreach (KeyValuePair<string, string> kvp in arguments)
            {
                Console.WriteLine("Parameter {0} = {1}", kvp.Key, kvp.Value);
            }
            Console.WriteLine("");

            if (arguments.ContainsKey("-DEBUG") && !(String.IsNullOrEmpty(arguments["-DEBUG"])) && arguments["-DEBUG"].ToUpper() == "YES")
            {

                TextWriterTraceListener writer = new TextWriterTraceListener(System.Console.Out);
                Trace.Listeners.Add(writer);
            }

            string userName = "";
            string userPassword = "";

            try
            {
                userName = arguments["-U"];
                userPassword = arguments["-P"];

            }
            catch
            {
                printUsage();
                return;
            }

            if (arguments.ContainsKey("-DOWNLOAD") && !(String.IsNullOrEmpty(arguments["-DOWNLOAD"])))
            {
                downloadFiles(arguments);
                return;
            }

            if (arguments.ContainsKey("-FILE") && !(String.IsNullOrEmpty(arguments["-FILE"])))
            {
                uploadSingleFileWithReturnInfo(arguments);
                return;
            }

            if (arguments.ContainsKey("-DIRECTORY") && !(String.IsNullOrEmpty(arguments["-DIRECTORY"])))
            {
                uploadDirectory(arguments);
                return;
            }

            if (arguments.ContainsKey("-L") && !(String.IsNullOrEmpty(arguments["-L"])))
            {
                switch (arguments["-L"])
                {
                    case "A":
                        listAlbums(arguments);
                        break;
                    case "C":
                        listCategories(arguments);
                        break;

                    case "SC":
                        listSubCategories(arguments);
                        break;
                    default:
                        {
                            Console.WriteLine("Invalid argument for -L. Invalid arg is {0}", arguments["-L"]);
                            printUsage();
                            return;
                        }
                }
                return;
            }

            if (arguments.ContainsKey("-C") && !(String.IsNullOrEmpty(arguments["-C"])))
            {
                CreateAlbum(arguments);
                return;
            }

            if (arguments.ContainsKey("-II") && !(String.IsNullOrEmpty(arguments["-II"])))
            {
                showImageInfo(arguments);
                return;
            }

            if (arguments.ContainsKey("-IID") && !(String.IsNullOrEmpty(arguments["-IID"])))
            {
                showImageInfoWithImages(arguments);
                return;
            }

            if (arguments.ContainsKey("-DELETEIMAGEID") && !(String.IsNullOrEmpty(arguments["-DELETEIMAGEID"]))
                && arguments.ContainsKey("-DELETEIMAGEKEY") && !(String.IsNullOrEmpty(arguments["-DELETEIMAGEKEY"])))
            {
                //blah
            }

        }
        private static void deleteImage(Dictionary<string, string> arguments)
        {
            string userName = "";
            string userPassword = "";
            string imageID = "";
            string imageKey = "";


            arguments.TryGetValue("-U", out userName);
            arguments.TryGetValue("-P", out userPassword);

            Debug.Assert(!String.IsNullOrEmpty(userName));
            Debug.Assert(!String.IsNullOrEmpty(userPassword));

            if (!arguments.ContainsKey("-DELETEIMAGEID"))
                throw new ArgumentException("Must supply imageID in arguments to deleteImage");

            if (!arguments.ContainsKey("-DELETEIMAGEKEY"))
                throw new ArgumentException("Must supply imageKey in arguments to deleteImage");

            arguments.TryGetValue("-DELETEIMAGEID", out imageID);
            arguments.TryGetValue("-DELETEIMAGEKEY", out imageKey);

            DeleteImageArguments dia = new DeleteImageArguments(imageID, imageKey);

            SmugMugApi api = new SmugMugApi(userName, userPassword);
            api.DeleteSmugMugImage(dia);



            
        }




        private static void showImageInfoWithImages(Dictionary<string, string> arguments)
        {

            string userName = "";
            string userPassword = "";
            string albumName = "";

            arguments.TryGetValue("-U", out userName);
            arguments.TryGetValue("-P", out userPassword);

            Debug.Assert(!String.IsNullOrEmpty(userName));
            Debug.Assert(!String.IsNullOrEmpty(userPassword));

            if (!arguments.ContainsKey("-IID"))
                throw new ArgumentException("Must supply album name in arguments to showImageInfoWithImages");

            arguments.TryGetValue("-IID", out albumName);

            GetImagesArguments args = new GetImagesArguments();
            args.AlbumName = albumName;

            SmugMugApi api = new SmugMugApi(userName, userPassword);
            SmugMugImages images = api.GetImages(args);

            foreach (SmugMugImage i in images)
            {
                Console.WriteLine("ID: " + i.ImageInfo.ImageID + " Key: " + i.ImageInfo.ImageKey + " (" + i.ImageInfo.ImageCaption + ")");
                Console.WriteLine(i.ImageInfo.OriginalURL);
            }
            Console.WriteLine("");

        }
        private static void showImageInfo(Dictionary<string, string> arguments)
        {

            string userName = "";
            string userPassword = "";
            string albumName = "";

            arguments.TryGetValue("-U", out userName);
            arguments.TryGetValue("-P", out userPassword);

            Debug.Assert(!String.IsNullOrEmpty(userName));
            Debug.Assert(!String.IsNullOrEmpty(userPassword));

            if (!arguments.ContainsKey("-II"))
                throw new ArgumentException("Must supply album name in arguments to showImageInfo");

            arguments.TryGetValue("-II", out albumName);

            GetImagesInfoArguments args = new GetImagesInfoArguments();
            args.AlbumName = albumName;

            SmugMugApi api = new SmugMugApi(userName, userPassword);
            SmugMugImagesInfo images = api.GetImagesInfo(args);

            foreach (SmugMugImageInfo i in images)
            {
                Console.WriteLine("ID: " + i.ImageID + " Key: " + i.ImageKey + " (" + i.ImageCaption + ")");
                Console.WriteLine(i.OriginalURL);
            }
            Console.WriteLine("");

        }
        private static void downloadFiles(Dictionary<string, string> arguments)
        {

            string userName = "";
            string userPassword = "";
            string albumName = "";
            string folderToPutFilesIn = "";


            arguments.TryGetValue("-U", out userName);
            arguments.TryGetValue("-P", out userPassword);

            Debug.Assert(!String.IsNullOrEmpty(userName));
            Debug.Assert(!String.IsNullOrEmpty(userPassword));

            arguments.TryGetValue("-DOWNLOAD", out folderToPutFilesIn);

            if (!arguments.ContainsKey("-A"))
                throw new ArgumentException("Must supply album in arguments to downloadFiles");

            arguments.TryGetValue("-A", out albumName);


            DownloadImagesArguments args = new DownloadImagesArguments();
            args.DownloadLocation = folderToPutFilesIn;
            args.AlbumName = albumName;

            SmugMugApi Api = new SmugMugApi(userName, userPassword);
            Api.DownloadImages(args);


        }
        private static void CreateAlbum(Dictionary<string, string> arguments)
        {
            string userName = "";
            string userPassword = "";

            arguments.TryGetValue("-U", out userName);
            arguments.TryGetValue("-P", out userPassword);

            Debug.Assert(!String.IsNullOrEmpty(userName));
            Debug.Assert(!String.IsNullOrEmpty(userPassword));

            try
            {
                SmugMugApi Api = new SmugMugApi(userName, userPassword);

                CreateAlbumArguments args = new CreateAlbumArguments();
                args.Name = arguments["-C"];

                string catagory, subcatagory, description;
                arguments.TryGetValue("-CATAGORY", out catagory);
                arguments.TryGetValue("-SUBCATAGORY", out subcatagory);
                arguments.TryGetValue("-DESCRIPTION", out description);
                if (!string.IsNullOrEmpty(catagory))
                {
                    args.Category = catagory;
                    if (!string.IsNullOrEmpty(subcatagory))
                        args.SubCategory = subcatagory;
                }
                if (!string.IsNullOrEmpty(description))
                    args.Description = description;


                Api.CreateAlbum(args);
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} in CreateAlbum.", e.Message.ToString());
                Console.WriteLine("");
            }

        }
        private static void uploadDirectory(Dictionary<string, string> arguments)
        {

            string directoryToUpload = "";
            string albumName = "";
            string user = "";
            string pass = "";
            string pictureCaption = "";
            string pictureKeywords = "";
            string purge = "FALSE";

            arguments.TryGetValue("-U", out user);
            arguments.TryGetValue("-P", out pass);
            arguments.TryGetValue("-DIRECTORY", out directoryToUpload);
            arguments.TryGetValue("-A", out albumName);
            arguments.TryGetValue("-CAPTION", out pictureCaption);
            arguments.TryGetValue("-KEYWORDS", out pictureKeywords);

            arguments.TryGetValue("-PURGE", out purge);

            Debug.Assert(!(String.IsNullOrEmpty(user)));
            Debug.Assert(!(String.IsNullOrEmpty(pass)));
            Debug.Assert(!(String.IsNullOrEmpty(directoryToUpload)));
            Debug.Assert(!(String.IsNullOrEmpty(albumName)));




            if (Directory.Exists(directoryToUpload))
            {
                try
                {
                    SmugMugApi Api = new SmugMugApi(user, pass);
                    List<string> fileList = new List<string>();
                    PostPicturesToSmugMugArguments args = new PostPicturesToSmugMugArguments();

                    args.AlbumName = albumName;
                    if (!String.IsNullOrEmpty(pictureCaption)) args.Caption = pictureCaption;
                    if (!String.IsNullOrEmpty(pictureKeywords)) args.Keywords = pictureKeywords;
                    if (!String.IsNullOrEmpty(purge)) args.DeleteAfterUpload = (purge == "TRUE" ? true : false);


                    fileList = Utilities.getFileListFromDirectory(directoryToUpload);

                    Console.WriteLine("Uploading {0} file" + (fileList.Count > 1 ? "s" : "") + " to smugmug. ", fileList.Count);

                    Api.PostPicturesToSmugMug(fileList, args);

                    Console.WriteLine("Operation completed");
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} in uploadDirectory.", e.Message.ToString());
                    Console.WriteLine("");
                }
            }

        }


        private static void uploadSingleFileWithReturnInfo(Dictionary<string, string> arguments)
        {
            string fileToUpload = "";
            string albumToSendFilesTo = "";
            string userName = "";
            string userPassword = "";
            string pictureCaption = "";
            string pictureKeywords = "";


            arguments.TryGetValue("-FILE", out fileToUpload);
            arguments.TryGetValue("-A", out albumToSendFilesTo);
            arguments.TryGetValue("-U", out userName);
            arguments.TryGetValue("-P", out userPassword);
            arguments.TryGetValue("-CAPTION", out pictureCaption);
            arguments.TryGetValue("-KEYWORDS", out pictureKeywords);


            if (String.IsNullOrEmpty(albumToSendFilesTo))
                throw new ArgumentException("Must supply album name to send files to");


            if (File.Exists(fileToUpload))
            {
                try
                {
                    SmugMugApi Api = new SmugMugApi(userName, userPassword);
                    List<string> fileList = new List<string>();
                    PostPicturesToSmugMugArguments parameters = new PostPicturesToSmugMugArguments();

                    fileList.Add(fileToUpload);
                    parameters.AlbumName = albumToSendFilesTo;
                    if (!String.IsNullOrEmpty(pictureCaption)) parameters.Caption = pictureCaption;
                    if (!String.IsNullOrEmpty(pictureKeywords)) parameters.Keywords = pictureKeywords;

                    Console.WriteLine("Uploading {0} file" + (fileList.Count > 1 ? "s " : " ") + "to smugmug.  This may take a while.", fileList.Count);

                    SmugMugImagesInfo info = Api.PostPicturesToSmugMugWithReturnInfo(fileList, parameters);
                    Console.WriteLine(info[0].ImageID + " " + info[0].ImageKey);
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} in uploadSingleFile.", e.Message.ToString());
                    Console.WriteLine("");
                }

                Console.WriteLine("Operation completed");

            }
        }


        private static void uploadSingleFile(Dictionary<string, string> arguments)
        {
            string fileToUpload = "";
            string albumToSendFilesTo = "";
            string userName = "";
            string userPassword = "";
            string pictureCaption = "";
            string pictureKeywords = "";


            arguments.TryGetValue("-FILE", out fileToUpload);
            arguments.TryGetValue("-A", out albumToSendFilesTo);
            arguments.TryGetValue("-U", out userName);
            arguments.TryGetValue("-P", out userPassword);
            arguments.TryGetValue("-CAPTION", out pictureCaption);
            arguments.TryGetValue("-KEYWORDS", out pictureKeywords);


            if (String.IsNullOrEmpty(albumToSendFilesTo))
                throw new ArgumentException("Must supply album name to send files to");


            if (File.Exists(fileToUpload))
            {
                try
                {
                    SmugMugApi Api = new SmugMugApi(userName, userPassword);
                    List<string> fileList = new List<string>();
                    PostPicturesToSmugMugArguments parameters = new PostPicturesToSmugMugArguments();

                    fileList.Add(fileToUpload);
                    parameters.AlbumName = albumToSendFilesTo;
                    if (!String.IsNullOrEmpty(pictureCaption)) parameters.Caption = pictureCaption;
                    if (!String.IsNullOrEmpty(pictureKeywords)) parameters.Keywords = pictureKeywords;

                    Console.WriteLine("Uploading {0} file" + (fileList.Count > 1 ? "s " : " ") + "to smugmug.  This may take a while.", fileList.Count);

                    Api.PostPicturesToSmugMug(fileList, parameters);
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0} in uploadSingleFile.", e.Message.ToString());
                    Console.WriteLine("");
                }

                Console.WriteLine("Operation completed");

            }
        }
        private static void listCategories(Dictionary<string, string> arguments)
        {

            string userName = "";
            string userPassword = "";

            arguments.TryGetValue("-U", out userName);
            arguments.TryGetValue("-P", out userPassword);

            Debug.Assert(!String.IsNullOrEmpty(userName));
            Debug.Assert(!String.IsNullOrEmpty(userPassword));

            try
            {

                SmugMugApi Api = new SmugMugApi(userName, userPassword);


                Dictionary<int, string> categories = Api.GetCategories();
                Console.WriteLine("Categories");
                foreach (KeyValuePair<int, string> kvp in categories)
                {
                    Console.WriteLine(kvp.Value);

                }

            }
            catch (Exception e)
            {
                Console.WriteLine("{0} in listCategories.", e.Message.ToString());
                Console.WriteLine("");
            }

        }
        private static void listSubCategories(Dictionary<string, string> arguments)
        {

            string userName = "";
            string userPassword = "";

            arguments.TryGetValue("-U", out userName);
            arguments.TryGetValue("-P", out userPassword);

            Debug.Assert(!String.IsNullOrEmpty(userName));
            Debug.Assert(!String.IsNullOrEmpty(userPassword));

            try
            {

                SmugMugApi Api = new SmugMugApi(userName, userPassword);


                Dictionary<int, string> categories = Api.GetCategories();
                Console.WriteLine("Categories");
                foreach (KeyValuePair<int, string> kvp in categories)
                {

                    Console.WriteLine(kvp.Value);
                    Dictionary<int, string> subCategories = Api.GetSubCategories(kvp.Value);
                    if (subCategories.Count > 0)
                    {
                        Console.WriteLine("Subcategories:");
                        foreach (KeyValuePair<int, string> subcat in subCategories)
                        {
                            Console.WriteLine("\t" + subcat.Value);
                        }
                    }
                    else
                    {
                        Console.WriteLine("category has no subcategories");
                    }

                }

            }
            catch (Exception e)
            {
                Console.WriteLine("{0} in listSubCategories.", e.Message.ToString());
                Console.WriteLine("");
            }

        }
        private static void listAlbums(Dictionary<string, string> arguments)
        {

            string userName = "";
            string userPassword = "";

            arguments.TryGetValue("-U", out userName);
            arguments.TryGetValue("-P", out userPassword);

            Debug.Assert(!String.IsNullOrEmpty(userName));
            Debug.Assert(!String.IsNullOrEmpty(userPassword));

            try
            {
                SmugMugApi Api = new SmugMugApi(userName, userPassword);

                List<SmugMugAlbumInfo> albums = Api.GetAlbums();
                Console.WriteLine("Albums");
                foreach (SmugMugAlbumInfo info in albums)
                {
                    Console.WriteLine(info.AlbumName);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} in listAlbums.", e.Message.ToString());
                Console.WriteLine("");
            }




        }
        private static void printUsage()
        {
            Console.WriteLine("stsm: SmugMugAPIWrapper test utility version {0}", Assembly.GetExecutingAssembly().GetName().Version);
            Console.WriteLine("\nusage:");
            Console.WriteLine("stsm -U username@example.com -P password [-FILE filename|-DIRECTORY directoryname] [-A albumname]\n     [-C albumname -CATEGORY categoryname -SUBCATAGORY subcatagoryname] [-L A|C]");
            Console.WriteLine("     -U username");
            Console.WriteLine("     -P password");
            Console.WriteLine("     -FILE filename (fully qualified.  Can be a wildcard");
            Console.WriteLine("     -DIRECTORY directory (fully qualified.  Can't use with -FILE");
            Console.WriteLine("     -A albumname");
            Console.WriteLine("     -C Create album");
            Console.WriteLine("     -CATEGORY Category to put album in (will create if necessary). Only with -A");
            Console.WriteLine("     -SUBCATEGORY SubCategory to put album in (will create if necessary).  Only with -A");
            Console.WriteLine("     -DESCRIPTION description of the album");
            Console.WriteLine("     -L [A|C|SC] List Albums (if -L A) or Categories (if -L C) or subcategories (if -L SC)");
            Console.WriteLine("     -II albumname (lists image info for the given album");
            Console.WriteLine("     -CAPTION \"caption in quotes\" (with -FILE or -DIRECTORY)");
            Console.WriteLine("     -KEYWORDS \"keywords,separated,by,commas,and,in,quotes\" (with -F or -D)");
            Console.WriteLine("     -DOWNLOAD directory.  Downloads files from a given album to a directory.  Must be used with -A");
            Console.WriteLine("     -DEBUG [YES|NO] prints debug info.  Default is NO, can be combined with any other options.");
            Console.WriteLine("");


        }

    }
}

